"""
Logging module.
"""
import sys
import getpass
import logging
import tempfile

# When running python from cron, the logger seems to throw exceptions. This
# suppresses those exceptions (and does not appear to have detrimental effects
# on the logging output).
logging.raiseExceptions = False

#FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
FORMAT = '%(asctime)s %(name)s %(filename)s %(lineno) -12s %(levelname)-8s %(message)s'

# The _user under which this python-code is running.
# (This is used to make non-colliding log-filenames to elide permissions
#    gremlins in logging.)
_user = 'noname'
try:
    _user = getpass.getuser()
except:
    pass

logging.basicConfig(level=logging.DEBUG,
                    format=FORMAT,
                    datefmt='%m-%d %H:%M',
                    filename=tempfile.gettempdir() + '/python-%s.log' % _user,
                    filemode='a')

CONSOLE = logging.StreamHandler()

# set a format which is simpler for console use
FORMATTER = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

# tell the handler to use this format
CONSOLE.setFormatter(FORMATTER)

## add the handler to the root logger
#logging.getLogger('').addHandler(CONSOLE)

INFO = logging.INFO
DEBUG = logging.DEBUG
WARN = logging.WARN

# set the default level to info
CONSOLE.setLevel(DEBUG)

def set_level(log_level):
    """Set the logging level.
    INFO
    DEBUG
    WARN
    """
    CONSOLE.setLevel(log_level)
    
def get_logger(module_name):
    """Returns a logger associated with the specified module name."""
    return logging.getLogger(module_name)
